﻿using HBMDoc.util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinHBM.Utils;

namespace HBMDoc
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();

            UserInfo userinfo = UserInfo.INSTANCE;
            if(userinfo.LoginId != null && userinfo.LoginId != "")
            {
                this.txtMobile.Text = userinfo.LoginId;
                this.txtPassword.Text = userinfo.Password;
            }

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            
           string strMobile = txtMobile.Text.ToString();
           string strPassword = txtPassword.Text.ToString();

            if (string.IsNullOrEmpty(strMobile))
            {
                MessageBox.Show("手机号为空");
                return;
            }

            if (string.IsNullOrEmpty(strPassword))
            {
                MessageBox.Show("密码为空");
                return;

            }
           
           JObject loginJObject = UtilData.CreateJson("login_id", strMobile, "password", strPassword, "role", "master");
           JObject result =  UtilRequest.DoRequest("/api/auth/login",UtilRequest.RequestMethod.POST,loginJObject);

            if (result.Value<int>("errcode")==0) {


                UserInfo userinfo = UserInfo.INSTANCE;
                userinfo.LoginId = strMobile;
                userinfo.Password = strPassword;
                userinfo.commit();

                UtilRequest.TokenHolder.isLogin = true;
                UtilRequest.TokenHolder.Token = result.Value<JObject>("contents").Value<string>("token");

                FormMain formMain = new FormMain(this);
                formMain.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show(result.Value<string>("message"));
            }
        }
    }
}
